<template>
  <el-dialog v-model="dialogVisible" :title="dialogTitle" width="900" :close-on-press-escape="false" :close-on-click-modal="false" center>
    <el-form ref="formRef" :model="formData" :rules="rules" label-width="120px" class="specialty-form" @submit.prevent="handleSubmit">
      <!-- 基本信息 -->
      <div class="form-section">
        <h3 class="section-title">基本信息</h3>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="标题" prop="title">
              <el-input v-model="formData.title" placeholder="请输入标题" clearable />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="描述" prop="description">
              <el-input v-model="formData.description" placeholder="请输入描述" clearable />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="链接地址" prop="linkUrl">
              <el-input v-model="formData.linkUrl" placeholder="请输入链接地址" clearable />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="排序" prop="orderNum">
              <el-input v-model="formData.orderNum" placeholder="请输入排序" clearable />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="状态" prop="isEnabled">
              <el-switch v-model="formData.isEnabled" active-text="启用" inactive-text="禁用" />
            </el-form-item>
          </el-col>
        </el-row>
      </div>
      <!-- 图片 -->
      <div class="form-section">
        <h3 class="section-title">图片</h3>
        <el-form-item label="图片" prop="imageUrls">
          <el-upload :file-list="imageFileList" :headers="fileHeader" :limit="1" :action="formAction" list-type="picture-card" :on-success="handleImageUpload" :on-remove="handleImageRemove">
            <el-icon><Plus /></el-icon>
          </el-upload>
        </el-form-item>
      </div>
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button type="primary" size="large" @click="submitForm" :loading="submitting"> {{ editMode ? '保存' : '发布' }} </el-button>
        <el-button size="large" @click="() => (dialogVisible = false)">关闭</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script lang="ts" setup>
import { ref, reactive, nextTick, computed } from 'vue'
import { ElMessage, ElMessageBox, dayjs } from 'element-plus'
import { Plus } from '@element-plus/icons-vue'
import http from '@/apis/banner'
import type { FormInstance, FormRules, UploadFile, UploadStatus, UploadProps } from 'element-plus'

import { useUserStore } from '@/stores/user'
const userStore = useUserStore()

const user = computed(() => userStore.userInfo)
// 表单引用
const formRef = ref<FormInstance>()
const inputRef = ref()

const submitting = ref(false)
const host = import.meta.env.VITE_BASE_URL

const formAction = ref(host + '/api/sysFile/uploadFile')
const fileHeader = ref({
  Authorization: 'Bearer ' + localStorage.getItem('token')
})
const imageUrls = new Array()
const imageFileList = ref<UploadFile[]>([])
// 表单数据
const formData = ref({
  title: '',
  orderNum: 10,
  description: '',
  linkUrl: '',
  isEnabled: true,
  imageUrl: ''
})

const handleImageUpload = (response: any) => {
  // console.log('Logo上传结果:', response)
  let { code, message, result } = response
  if (code === 200) {
    let url = `${host}/${result.url}`
    formData.value.imageUrl = url
    imageUrls.push(url)
    ElMessage.success('上传成功')
    console.log('上传成功', url)
  } else {
    ElMessage.error('上传失败: ' + response.message)
  }
}

const handleImageRemove = (file: any) => {
  formData.value.imageUrl = ''
}

// 表单验证规则
const rules: FormRules = {
  title: [
    { required: true, message: '请输入标题', trigger: 'blur' },
    { min: 2, max: 50, message: '长度在 2 到 50 个字符', trigger: 'blur' }
  ],
  orderNum: [
    { required: true, message: '请输入排序', trigger: 'blur' },
    { pattern: /^[A-Z0-9]+$/, message: '只能包含大写字母和数字', trigger: 'blur' }
  ]
}

// 表单操作方法
const handleSubmit = async () => {
  if (!formRef.value) return

  try {
    await formRef.value.validate()

    const submitData = { ...formData.value }
    submitData.imageUrl = JSON.stringify(imageUrls)
    http
      .create(submitData)
      .then((response) => {
        const { code, message } = response.data
        if (code !== 200) {
          throw new Error(message || '提交失败')
        }
        ElMessage.success('商品信息保存成功！')
        // 重置表单
        formRef.value?.resetFields()
      })
      .catch((error) => {
        ElMessage.error(error.message || '提交失败，请稍后再试')
      })
    // console.log('提交数据:', submitData)
  } catch (error) {
    ElMessage.error('请检查表单填写是否正确')
  }
}

// 提交表单
const submitForm = async () => {
  if (!formRef.value) return

  try {
    await formRef.value.validate()
    submitting.value = true

    // 构造提交数据
    let submitData = {
      ...formData.value
    }
    if (editMode.value) {
      submitUpdate(submitData)
    } else {
      submitCreate(submitData)
    }
  } catch (error) {
    ElMessage.error('请检查表单填写是否完整')
  } finally {
    submitting.value = false
  }
}

const submitCreate = (submitData: any) => {
  // API调用
  http
    .create(submitData)
    .then((response) => {
      let { code, message } = response.data
      if (code != 200) {
        ElMessage.error(message)
        return
      }
      ElMessage.success('发布成功！')
      dialogVisible.value = false
      emit('create', submitData)
    })
    .catch(() => {
      ElMessage.error('发布失败，请稍后重试')
    })
}
const submitUpdate = (submitData: any) => {
  let keys = ['updateTime', 'updateUserId', 'updateUserName', 'userId']
  keys.forEach((t) => delete submitData[t])
  submitData.status = submitData.status ?? 100
  http
    .update(submitData)
    .then((response) => {
      let { code, message } = response.data
      if (code != 200) {
        ElMessage.error(message)
        return
      }
      ElMessage.success('更新成功！')
      dialogVisible.value = false
      emit('update', submitData)
    })
    .catch(() => {
      ElMessage.error('更新失败，请稍后重试')
    })
}
// 重置表单
const resetForm = () => {
  ElMessageBox.confirm('确定要重置表单吗？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    formRef.value?.resetFields()
    formData.value.imageUrl = ''
    ElMessage.success('表单已重置')
  })
}

const dialogTitle = ref('新增数据')
const emit = defineEmits(['update', 'create'])
const editMode = ref(false)
const dialogVisible = ref(false)
const handleCreate = () => {
  dialogVisible.value = true
  dialogTitle.value = '新增数据'
  editMode.value = false
}
const handleModify = (obj: any) => {
  dialogVisible.value = true
  formData.value = { ...obj }
  editMode.value = true
  dialogTitle.value = '编辑数据'
  imageFileList.value = []
  if (obj.imageUrl) {
    imageFileList.value = [{ url: obj.imageUrl, name: '轮播图', status: 'success', uid: 10001 }]
  }
  //   console.log(obj)
}

defineExpose({
  handleCreate,
  handleModify
})
</script>
<style>
.form-container {
  max-width: 800px;
  margin: 0 auto;
  padding: 20px;
}

.form-card {
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
}

.card-header {
  text-align: center;
}

.card-header h2 {
  margin: 0 0 8px 0;
  color: #303133;
  font-size: 24px;
  font-weight: 600;
}

.card-header p {
  margin: 0;
  color: #909399;
  font-size: 14px;
}

.job-form {
  display: flex;
  flex-wrap: wrap;
}

.form-section {
  margin: 10px 10px;
  flex: 1 1;
  min-width: 400px;
  border-bottom: 1px solid #f0f0f0;
}

.form-section:last-child {
  border-bottom: none;
}

.section-title {
  margin: 0 0 20px 0;
  color: #409eff;
  font-size: 16px;
  font-weight: 600;
  padding-left: 8px;
  border-left: 3px solid #409eff;
}
.tags-container {
  display: flex;
  gap: 10px;
}
.tags-input {
  display: flex;
  flex-wrap: wrap;
  gap: 8px;
  align-items: center;
}

.tag-item {
  margin: 0;
}

.tag-input {
  width: 120px;
}

.avatar-uploader {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: border-color 0.3s;
}

.avatar-uploader:hover {
  border-color: #409eff;
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 100px;
  height: 100px;
  text-align: center;
  line-height: 100px;
}

.avatar {
  width: 100px;
  height: 100px;
  display: block;
  object-fit: cover;
}

.submit-section {
  padding: 20px 0px;
  display: flex;
  justify-content: center;
}

.submit-section .el-button {
  margin: 0 8px;
  min-width: 120px;
}

/* 预览样式 */
.job-preview {
  padding: 16px;
}

.preview-header {
  display: flex;
  align-items: center;
  margin-bottom: 20px;
  padding-bottom: 16px;
  border-bottom: 1px solid #f0f0f0;
}

.preview-avatar {
  width: 60px;
  height: 60px;
  border-radius: 8px;
  object-fit: cover;
  margin-right: 16px;
}

.preview-info h3 {
  margin: 0 0 8px 0;
  color: #303133;
  font-size: 18px;
}

.preview-info p {
  margin: 0;
  color: #909399;
  font-size: 14px;
}

.preview-details {
  margin-top: 16px;
}

.preview-tags {
  margin-top: 16px;
  display: flex;
  flex-wrap: wrap;
  gap: 8px;
}
</style>
